package sanshi.contect.chinaOofresp.exer1;

import java.util.ArrayList;

/**
 * 责任链模式：实现request与response的分开执行
 * 完全模拟servlet中的FilterChina
 * 这种不能在FilterChina的后面连接China
 */

public class ServletFilterChina {

    public static void main(String[] args) {
        FilterChina china = new FilterChina();
        china.add(new HTMLFilter()).add(new SensitiveFilter());

        Request request = new Request();
        request.str = "大家好：<script>，欢迎访问sanshi.ltd, 上班的时间996";

        Response response = new Response();
        response.str = "response";

        china.doFilter(request, response);
        System.out.println("request.str:" + request.str);
        System.out.println("response.str:" + response.str);


    }
}
class Request{
    String str;
}
class Response{
    String str;
}
interface Filter{
     boolean doFilter(Request request, Response response, FilterChina china);
}
class HTMLFilter implements Filter{

    @Override
    public boolean doFilter(Request request, Response response, FilterChina china) {

        request.str = request.str.replace('<', '[');
        request.str = request.str.replace('>', ']');
        china.doFilter(request, response);
        response.str += "-----> HTMLFilter";
        return true;
    }
}
class SensitiveFilter implements Filter{

    @Override
    public boolean doFilter(Request request, Response response, FilterChina china) {

        request.str = request.str.replace("996", "955");
        china.doFilter(request, response);
        response.str += "-----> SensitiveFilter";
        return true;
    }
}

class FilterChina{
    //使用指针控制Filter的调用
    int index = 0;
    ArrayList<Filter> filters = new ArrayList<>();

    public FilterChina add(Filter filter){
        filters.add(filter);
        return this;

    }

    /**
     * 在调用对应的doFilter的时候。使用一个指针来控制调用的指定的Filter。并且使用
     * @param request
     * @param response
     * @return
     */

    public boolean doFilter(Request request, Response response) {
        //当执行完最后一个Filter之后将不往下执行
        if (index == filters.size()) return false;
        Filter f = filters.get(index);
        index ++;
        f.doFilter(request, response, this);
        return true;
    }

}
